//--------------------

//接口服务器地址

const picUrl = "https://wjp.runvint.com/Areas/grnyapi/";
//测试服务器地址 
const serverUrl="https://wjp.runvint.com";

//-----------------------

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

module.exports = {
  formatTime: formatTime,
  // 此处调用可直接使用NetAPI.VehicleResManager(data).then(...)，第二个参数showLoading采用缺省，即默认使用加载，调用给false，即可屏蔽默认的加载框，js不支持方法重载，也是没办法
  request: (url,data, showLoading,mask) => {
    return request(url, data, showLoading == undefined ? true : showLoading, mask == undefined ? true : mask)
  },
  serverUrl:()=>{return serverUrl},
  picUrl:()=>{return picUrl},
  teamID: () => { return teamID },
  showToast:(title,icon)=>{
    showToast(title,icon==undefined?'success':icon);
  },
  checkLogin:(type)=>{
    return checkLogin(type==undefined?0:type);
  },
  navigateTo:(url)=>{
    navigateTo(url);
  },
  navigateBack:(delta)=>{
    navigateBack(delta==undefined?1:delta);
  },
  mapKey:()=>{
    return mapKey;
  }
}



//统一发送post请求  
//url:只需传接口的虚拟路径
//data:参数 json格式{"":""}
//showLoading: 是否显示loadding层，不传的话默认显示
//mask: 是否允许穿透 默认true
const request = (url, data, showLoading,mask) => {
  let _url = serverUrl + url;
  return new Promise((resolve, reject) => {
    // 由调用者控制是否需要显示加载对话框
    if (showLoading) {
      wx.showLoading({
        title: '正在加载',
        mask: mask
      })
    }
    getToken().then(function(res){
        if (res != 'error') {  //登录成功
          data.token = getApp().globalData.token;
            data.gps = getApp().globalData.home_gps;
        data.version="1.0";
        wx.request({
          url: _url,
          method: 'post',   
          data: data,
          dataType: "json",
          header: { 'content-type': 'application/x-www-form-urlencoded;charset=utf-8' },
          success(res) {
            wx.hideLoading();
            resolve(res.data)
          },
          fail(err) {
            console.error('网络请求失败', err)
            wx.hideLoading();
            wx.showModal({
              title: '提示',
              content: 'postErr:' +JSON.stringify(err),
              showCancel: false
            })
          }
        })
      }
 
    });
  
  })
}

//获取token
const getToken = () =>{

  return new Promise((resolve, reject) => {
    var token = getApp().globalData.token;
    var check=false;
    if(token!=''){
      wx.checkSession({
        success () {
          resolve(token);
        },
        fail () {
          check=true;
        }
      })
    }else{
      check=true;
    }
   
    if(check){
      wx.login({
        success: function (res) {
          if (res.code) {
            wx.request({
              url: serverUrl+'/grnyapi/User/WxLogin',
              data: {
                code: res.code,
                checkLogin: 0
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded' // 默认值
              },
              method: "post",
              dataType: "json",
              success: function (res) {
                // 登录成功
                if (res.data.code==1) {
                  getApp().globalData.token = res.data.data.token;// 服务器回包内容
                  getApp().globalData.isNewUser=res.data.data.isNewUser;
                  resolve(res.data.data.token)
                }else{
                  wx.showModal({
                    title: '提示',
                    content: '登录失败',
                    showCancel: false
                  })
                  reject("error")
                }
               
              },
              fail: function (e) {
                wx.showModal({
                  title: '提示',
                  content: 'WxLoginErr:' +JSON.stringify(e),
                  showCancel: false
                })
                reject("error")
              }
            })
          } else {
            wx.showModal({
              title: '提示',
              content: '用户授权失败',
              showCancel: false
            })
            reject("error")
          }
        }
      })
    }
  })

}

const showToast=(title,icon)=>{
  wx.showToast({
    title:title,
    icon:icon
  });
}

//未授权的没有登录  返回false 未登录  type：0返回上一页 1返回首页
const checkLogin=(type)=>{
    var check = true;
    if (getApp().globalData.user_name == '') {
      check = false;
      navigateTo('/pages/login/login?type='+type);
      
    }
    return check;
}

//页面跳转  
const navigateTo=(url)=>{
  wx.showLoading({
      title:"正在跳转",
      mask:false
    });

    wx.navigateTo({
      url:url
    });

    wx.hideLoading();
}

//返回前几页。默认上一页
const navigateBack=(delta)=>{
    wx.navigateBack({
      delta:delta
    });
}